package com.qd.common.sys.domain.sendmsg;


import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author sjk
 */
@Data
@Accessors(chain = true)
@Slf4j
public class MsgReceiver {
    public static final short CLASSIFY_USER = 1;

    /**
     * 接收者标识
     */
    private String id;

    /**
     * 接收者类型
     */
    private short type;

    /**
     * 接收者账号分类
     */
    private int classify;

    /**
     * 接收者属性
     */
    private MsgContentProperties properties;

    /**
     * 动态url属性
     */
    private UrlParams urlParams;

    public void free() {
        id = null;
        Optional.ofNullable(properties).ifPresent(MsgContentProperties::free);
        Optional.ofNullable(urlParams).ifPresent(UrlParams::free);
    }


    public boolean isEmptyProperties() {
        if (properties == null) {
            return true;
        }
        return properties.isEmpty();
    }

    public MsgContentProperties getProperties() {
        if (properties == null) {
            properties = new MsgContentProperties();
        }
        return properties;
    }

    public boolean isEmptyUrlParams() {
        if (urlParams == null) {
            return true;
        }
        return urlParams.isEmpty();
    }

    public UrlParams getUrlParams() {
        if (urlParams == null) {
            urlParams = new UrlParams();
        }
        return urlParams;
    }

    public void read(JSONObject content) {
        id = content.getString("id");
        type = content.getShortValue("type");
        classify = content.getShortValue("classify");
        readProperties(content);
        readUrlParams(content);
    }

    private void readUrlParams(JSONObject content) {
        JSONObject jsonObject = content.getJSONObject("urlParams");
        if (jsonObject != null) {
            urlParams = new UrlParams();
            urlParams.read(jsonObject);
        }
    }

    private void readProperties(JSONObject content) {
        JSONObject jsonObject = content.getJSONObject("properties");
        if (jsonObject != null) {
            properties = new MsgContentProperties();
            properties.read(jsonObject);
        }
    }

    public void write(JSONObject content) {
        content.put("id", id);
        content.put("type", type);
        content.put("classify", classify);

        if (properties != null && !properties.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            content.put("properties", jsonObject);
            properties.write(jsonObject);
        }

        if (urlParams != null && !urlParams.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            content.put("urlParams", jsonObject);
            urlParams.write(jsonObject);
        }
    }
}
